package ndquangr.intern.ringtonemaker;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import ndquangr.intern.ringtonemaker.listitems.MusicInfoAdapter;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.TextView;

public class MusicPlayerActivity extends Activity {
	
	private ListView ls_playlist;
	private ImageButton btn_previous;
	private ImageButton btn_play;
	private ImageButton btn_next;
	private ImageButton btn_edit;
	private TextView tv_songTitle;
	private TextView tv_total;
	private TextView tv_progress;
	private SeekBar sb_playingStatus;
	
	private List<String> songs;// = new ArrayList<String>();
	private List<String> songTitles;
	private List<String[]> adapterInfo;
	private MusicInfoAdapter adtMusicInfo;
	
	private MediaPlayer mp = null;
	private Handler handler;
	private int currentItem = -1;
	private String currentFilePath = "";
	private boolean IS_STARTED;	
	private final int INTERVAL = 1000;
	private boolean FROM_OTHER_ACTIVITY;
	private Context mContext;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);        
        boolean customTitleSupported = getWindow().requestFeature(Window.FEATURE_CUSTOM_TITLE);
        setContentView(R.layout.music_player);

        mContext = this;
        if ( customTitleSupported ) {
            getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.music_player_titlebar);
        }
        
        songs = new ArrayList<String>();
        songTitles = new ArrayList<String>();
        adapterInfo = new ArrayList<String[]>();
     
        // Get information from intent
        Bundle extras = getIntent().getExtras();
		if (extras != null) {						
			// Get specific songs base on tag
			String filePath = extras.getString("uri");	
			if (filePath != null) {
				currentFilePath = filePath;
				FROM_OTHER_ACTIVITY = true;
			}
		}
        
        getControlInstances();
        setActionListener();
        setupMediaPlayer();
        initialPlaylist();
        
        if (FROM_OTHER_ACTIVITY) {
        	startPlayMusic();
        }
	}

	private void getControlInstances() {
		// TODO Auto-generated method stub
		btn_previous = (ImageButton)findViewById(R.id.btn_musicPlayer_Previous);
		btn_play = (ImageButton)findViewById(R.id.btn_musicPlayer_Start);
		btn_next = (ImageButton)findViewById(R.id.btn_musicPlayer_Next);
		btn_edit = (ImageButton)findViewById(R.id.btn_musicPlayer_Edit);
		tv_songTitle = (TextView) findViewById(R.id.tv_musicPlayer_songtitle);
		ls_playlist = (ListView)findViewById(R.id.ls_musicPlayer_list);
		tv_total = (TextView) findViewById(R.id.tv_musicPlayer_total_time);
		tv_progress = (TextView) findViewById(R.id.tv_musicPlayer_progress);
		sb_playingStatus = (SeekBar) findViewById(R.id.sb_musicPlayer_Progress);
	}
	
	private void setActionListener() {
		// TODO Auto-generated method stub
		btn_previous.setOnClickListener(btnPreviousClick);
		btn_play.setOnClickListener(btnPlayClick);
		btn_next.setOnClickListener(btnNextClick);
		btn_edit.setOnClickListener(btnEditClick);
		sb_playingStatus.setOnSeekBarChangeListener(playProgress_Listener);
		ls_playlist.setOnItemClickListener(lsItemClick);
		tv_songTitle.setText("No song selected");
	}
	
	
	/** Get all songs in sd card with specific condition in parameter */
	private void initialPlaylist() {
		
		String[] projection = {
		        MediaStore.Audio.Media.DATA,
		        MediaStore.Audio.Media.TITLE,	
		        MediaStore.Audio.Media.DURATION
		};
	
		Cursor cursor = this.managedQuery(
		        MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
		        projection,
		        null,
		        null,
		        MediaStore.Audio.Media.TITLE);
	
		songs = new ArrayList<String>();
		songTitles = new ArrayList<String>();
		
		String[] tempString;
		String tempPath;
		long duration;
		while(cursor.moveToNext()){
			tempString = new String [2];
			tempPath = cursor.getString(0);
			if (FROM_OTHER_ACTIVITY && tempPath.equals(currentFilePath)) {
				currentItem = songs.size();
			}
		    songs.add(tempPath);		    
			songTitles.add(cursor.getString(1));
			tempString[0] = cursor.getString(1);
			duration = cursor.getInt(2);
			/*
			if (duration == 0) {
				try {
					mp.reset();
					mp.setDataSource(tempPath);
					mp.prepare();
					duration = mp.getDuration();
				} catch (IllegalArgumentException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IllegalStateException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}				
			}
			*/
			
			tempString[1] = getTimeString(duration);
			adapterInfo.add(tempString);			
		}
		
		if (adapterInfo != null) {
			adtMusicInfo = new MusicInfoAdapter(this, R.layout.music_item, new ArrayList<String[]>(adapterInfo));
			ls_playlist.setAdapter(adtMusicInfo);
			mp.reset();
        }
	}
	
	//
	public static String getTimeString(long duration) {
		String str = "";
		int min = (int) ((duration/1000)/60);
		if (min < 10) {
			str = str + "0" + min + ":";
		} else {
			str = str + min + ":";
		}
		
		int sec = (int) ((duration/1000)%60);
		if (sec < 10) {
			str = str + "0" + sec;
		} else {
			str = str + sec;
		}
		return str;
	}
	
	/**
     * Setup media player
     */
	private void setupMediaPlayer() {
		mp = new MediaPlayer();
        mp.setLooping(false);
        handler = new Handler();
        mp.setOnCompletionListener(mediaComplete_Listener);
	}
	
	/**
	 * Start playing a song
	 * @param item: index of the song in the list
	 */
	private void startPlayMusic(){
		try {	
			// Prepare the media player
			mp.reset();
			mp.setDataSource(currentFilePath);			
			mp.prepare();

			int time = mp.getDuration();
			sb_playingStatus.setMax(time);			
			tv_total.setText(getTimeString(time));
			sb_playingStatus.setProgress(0);
			handler.postDelayed(seekbarTask, INTERVAL);
			btn_play.setImageResource(R.drawable.media_playback_pause);
			tv_songTitle.setText(songTitles.get(currentItem));
			IS_STARTED = true;
			
			mp.start();
			
			// Set up the progress bar
			/*
			int time = mp.getDuration();
			playingStatus.setMax(time);			
			tv_total.setText(stringForTime(time));
			playingStatus.setProgress(0);
			handler.postDelayed(seekbarTask, INTERVAL);
			
			// Set song information to the labels
			String songInfos = GetMusicInformation();
			String[] items = songInfos.split("\n");
			tv_song_tittle.setText(items[0]);
			tv_song_album.setText(items[1]);
			tv_song_artist.setText(items[2]);
			tv_song_composer.setText(items[3]);
			tv_song_year.setText(items[4]);			
			*/
		} catch (IOException e) {
			Log.v(getString(R.string.app_name), e.getMessage());
		}
	}
	
	private OnClickListener btnPlayClick = new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			if (!IS_STARTED) {
				if (currentItem > -1)
				{					
					startPlayMusic();
				}			
			} else {
				if (!mp.isPlaying()) {
					mp.start();
					btn_play.setImageResource(R.drawable.media_playback_pause);
				} else {
					mp.pause();
					btn_play.setImageResource(R.drawable.media_playback_start);
				}
			}
		}
	};
	
	private OnClickListener btnEditClick= new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			if (currentItem != -1) {
				 Intent myIntent = new Intent(mContext, EditAudioActivity.class);		
				 myIntent.putExtra("uri", songs.get(currentItem));
				 startActivity(myIntent);
			}
		}
	};
	
	/** Listener for media completed event */
    private OnCompletionListener mediaComplete_Listener = new OnCompletionListener(){
		@Override
		public void onCompletion(MediaPlayer mp) { 
			IS_STARTED = false;
		}
    };
    
    private OnItemClickListener lsItemClick = new OnItemClickListener() {
        public void onItemClick(AdapterView<?> adapter, View view,
                int position, long id) {
        	currentFilePath = songs.get(position);
        	currentItem = position;
        	
        	startPlayMusic();
          }
      };
      /**
  	 * Listener fo seekbar
  	 */
  	private OnSeekBarChangeListener playProgress_Listener = new OnSeekBarChangeListener() {
  		
  		@Override
  		public void onStopTrackingTouch(SeekBar seekBar) {
  			// TODO Auto-generated method stub
  			int progress = seekBar.getProgress();
  			mp.seekTo(progress);
  		}
  		
  		@Override
  		public void onStartTrackingTouch(SeekBar seekBar) {
  			// TODO Auto-generated method stub
  			
  		}
  		
  		@Override
  		public void onProgressChanged(SeekBar seekBar, int progress,
  				boolean fromUser) {
  			
  		}
  	};
  	
  	/**
	 * This is used for update seek bar progress and set the current played time in text view 
	 */
	private Runnable seekbarTask = new Runnable(){
		

		@Override
		public void run() {
			if (mp == null)
			{
				return;
			}
			int position = mp.getCurrentPosition();
			sb_playingStatus.setProgress(position);
			tv_progress.setText(getTimeString(position));
			handler.postDelayed(seekbarTask, INTERVAL);
		}
	};
	
	@Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
        	if (mp.isPlaying()) {
        		mp.release();
        		mp = null;
        	}
            return super.onKeyDown(keyCode, event);
        }
        return super.onKeyDown(keyCode, event);
    }
	
	/** Listener for next buttons */
    private OnClickListener btnNextClick = new OnClickListener() {
        @Override
		public void onClick(View v) {   
        	// Calculate next item based on shuffle status and size of the list
        	int nextItem;
        	  	
			if (currentItem > -1) {
				nextItem = currentItem + 1;
				if (nextItem >= songs.size()) {
					nextItem = 0;
				}
			} else {
				nextItem = 0;
				}
        	
			currentItem = nextItem;
			currentFilePath = songs.get(currentItem);
			
			// Set the media player to play new item
			startPlayMusic();
        }
    };
    
    /** Listener for previous buttons */
    private OnClickListener btnPreviousClick = new OnClickListener() {
    	@Override
 		public void onClick(View v) {  
    		// Calculate previous item based on shuffle status and size of the list
	   		int preItem;
	   		
			if (currentItem > -1 ) {
				preItem = currentItem - 1;
				if (preItem < 0) {
					preItem = songs.size() - 1;
				}
			} else {
				preItem = songs.size() - 1;
			}
	   		
			currentItem = preItem;
			currentFilePath = songs.get(currentItem);
			
			// Set the media player to play new item			
			startPlayMusic();	
			
    	}
	};
    
}
